package com.neusoft.neu24.his.hisapp.controller;

import com.neusoft.neu24.his.hisapp.entity.Member;
import com.neusoft.neu24.his.hisapp.service.IMemberService;
import com.neusoft.neu24.his.hisapp.service.impl.MemberService;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.util.List;
import java.util.function.Predicate;

public class GuaHaoController {

    IMemberService memberService =new MemberService();

    private static   List<Member> members ;

    private ObservableList<Member>  observableList ;
    private ReadOnlyObjectProperty<ObservableList<Member> > membersProperty =null;


    private ToggleGroup filterTG = new ToggleGroup();

    @Override
    public String toString() {
        return super.toString();
    }

    @FXML
    HBox vb_btnbox;
    @FXML
    ListView<Member> lv_members;


    @FXML
    public void initialize()
    {
//        加载数据
        members = memberService.selectAll();
//        可视化列表
        observableList =  FXCollections.observableArrayList(members);
//        对象属性
        membersProperty =  new SimpleObjectProperty<>(observableList);
        ReadOnlyObjectProperty<FilteredList<Member>> viewableMembersProperty =
                new SimpleObjectProperty<FilteredList<Member>>(
                        new FilteredList<>(membersProperty.get()
                        ));

        ObjectProperty<Predicate<? super Member>> filterProperty =
                viewableMembersProperty.get().predicateProperty();

        lv_members.itemsProperty().bind(viewableMembersProperty);
        @SuppressWarnings("unchecked")
        EventHandler<ActionEvent> toggleHandler = (event) -> {
            ToggleButton tb = (ToggleButton)event.getSource();
            Predicate<Member> filter = (Predicate<Member>)tb.getUserData();
            filterProperty.set( filter );
        };

        List<ToggleButton> tbs = members.stream()
                .map(  m -> m.getSex() )
                .distinct()
                .map( sex-> {
                    ToggleButton tb =new ToggleButton(sex);
                    tb.setToggleGroup( filterTG );
                    tb.setOnAction(toggleHandler);
                    tb.setUserData(
                            (Predicate<Member>)m-> m.getSex().equals(sex)
                    );
                    return   tb;

                }).collect(java.util.stream.Collectors.toList());

        vb_btnbox.getChildren().addAll(tbs);




    }
}
